<?php

use Illuminate\Database\Eloquent\ModelNotFoundException;

class AdminProductKeyController extends AdminController {

	public function getIndex(){
		Cache::forget('product_key-all-data');
		if(!Cache::has('product_key-all-data')){
			$data = ProductKey::join('product as p', 'p.id', '=', 'product_key.product_id')
					->select('p.name', 'product_key.id', 'product_key.key', 'product_key.created_at', 'product_key.updated_at')
					->whereNull('product_key.deleted_at')
					->orderBy('product_key.created_at', 'desc')
					->get();
			Cache::put('product_key-all-data', $data, 30);
		}

		$data = Cache::get('product_key-all-data');

		$this->layout->title = trans('productkey.list');
		$this->layout->content = View::make('admin.productkey.index', array('data' => $data));
	}

	public function getCreate(){
		$product = Product::orderBy('name')->lists('name', 'id');

		$this->layout->title = trans('productkey.create');
		$this->layout->content = View::make('admin.productkey.form', array('product' => $product));
	}

	public function getEdit($id){
		$this->layout->title = trans('productkey.edit');

		try{
			$model = new ProductKey;
			$productkey = $model->findOrFail($id);

			$product = Product::orderBy('name')->lists('name', 'id');

			$this->layout->content = View::make('admin.productkey.form', array('productkey' => $productkey, 'product' => $product));
		}catch(ModelNotFoundException $e){
			App::abort(404);
		}
	}

	public function postSave(){
		$this->layout = null;

		$data = Input::all();

		$model = new ProductKey;

		$validator = $model->validator($data);

		if($validator->fails()){
			if(isset($data['id']) && $data['id'] > 0){
				$url = 'admin/product-key/edit/' . $data['id'];
			}else{
				$url = 'admin/product-key/create/';
			}

			return Redirect::to($url)->withInput()->with('errors', $model->getErrorMessages());
		}else{
			$model->saveData($data);
			return Redirect::to('admin/product-key/');
		}
	}

	public function getDelete($id){
		$this->layout = null;

		try{
			$model = new ProductKey;
			$data = $model->findOrFail($id);
			$data->delete();
			Cache::pull('product_key-all-data');
			
			return Redirect::to('admin/product-key/')->with('message', trans('productkey.deleted'));
		}catch(ModelNotFoundException $e){
			App::abort(404);
		}
	}
}
